<template>
  <view>
    <button type="primary" @click="pay">支付</button>
    <button type="warn" @click="pay1">支付</button>
  </view>
</template>

<script>
  import {User} from '@/apis'
  import {utils} from '@/utils'
  export default {
    data: function() {
      
      return {
      }
    },
    methods: {
     pay () {
       let userInfo = uni.getStorageSync('userInfo')
       // 调用预下单接口 
       uni.showLoading({
         title: '加载中...'  
       })
       var orderNumber = utils.randomWord(false, 32)
       console.log('生成随机字符串： ' + orderNumber)
       
       User.prePayment({
         data: {
           form: {
             orderNumber: orderNumber,
             paymentFee: 1,
             openid: userInfo.openid
           },
           query: {},
           pagination: {}
         }
       }).then(res => {
         console.log('请求成功', res)
         uni.requestPayment({
           timeStamp: res.data.body.timeStamp,
           nonceStr: res.data.body.nonceStr,
           package: res.data.body.package,
           signType: 'MD5',
           paySign: res.data.body.paySign,
           success (res) {
             console.log('支付成功', res)
           },
           fail (err) {
             console.log('支付失败', err)
           }
         })
       }).catch(err => {
         console.error(err)
       })
     },
     pay1 () {
       let userInfo = uni.getStorageSync('userInfo')
       var orderNumber = utils.randomWord(false, 32)
       var goodsId = utils.randomWord(false, 16)
       console.log('生成随机字符串： ' + orderNumber)
       User.prePayment({
         data: {
           form: {
             device_info: '1',
             body: '商品描述',
             detail: '商品详情',
             out_trade_no: orderNumber,
             total_fee: 1,
             spbill_create_ip: '0.0.0.0',
             time_start: Date.now(),
             // time_expire: Date.now() + (30 * 1000 * 60),
             notify_url: 'http://www.weixin.qq.com/wxpay/pay.php',
             product_id: goodsId,
             openid: userInfo.openid
           }
         }
       }).then(res => {
         console.log('请求支付接口')
         console.log(res)
         let result = res.data.body
         uni.requestPayment({
           nonceStr: result.nonceStr,
           timeStamp: result.timeStamp,
           package: result.packageInfo,
           paySign: result.sign,
           signType: 'MD5',
           success (payRes) {
             console.log('支付完成')
             console.log(payRes)
           },
           fail (err) {
             console.log('支付失败');
             console.error(err)
           }
         })
       }).catch(err => {
         console.error(err)
       })
     }
    }
  }
</script>

<style>

</style>
